<template>
  <div class="table-box">
    <template v-if="dictTypeShow">
      <el-form ref="formRef" :model="searchParam" :inline="true">
        <el-form-item label="字典名称">
          <el-input v-model="searchParam.dictName" />
        </el-form-item>
        <el-form-item label="字典类型">
          <el-input v-model="searchParam.dictType" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="getDictTypeList"> 搜索 </el-button>
          <el-button :icon="Delete" @click="resetTypeList"> 重置 </el-button>
        </el-form-item>
      </el-form>
      <el-divider content-position="left">字典类型项</el-divider>
    </template>
    <template v-else>
      <el-descriptions border>
        <el-descriptions-item label="字典项">{{ TypeInfo.dictName }}</el-descriptions-item>
        <el-descriptions-item label="字典编号">{{ TypeInfo.dictType }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag v-if="TypeInfo.status === '0'" type="success">正常</el-tag>
          <el-tag v-if="TypeInfo.status === '1'" type="danger">关闭</el-tag>
        </el-descriptions-item>
      </el-descriptions>
      <el-divider content-position="left">字典数据项</el-divider>
    </template>
    <div class="table-header">
      <div class="header-button-lf">
        <el-button plain type="primary" :icon="CirclePlus" @click="btnAdd">新增</el-button>
        <el-button plain type="danger" :icon="Delete" @click="btnDelete">删除</el-button>
      </div>
      <div class="header-button-ri">
        <el-button :icon="Refresh" circle @click="refreshData" />
      </div>
    </div>
    <el-table class="dict-table" :data="tableData" border @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55" />
      <template v-if="dictTypeShow">
        <el-table-column align="center" prop="dictId" label="字典编号" />
        <el-table-column align="center" prop="dictName" label="字典名称" />
        <el-table-column align="center" prop="dictType" label="字典类型" />
        <el-table-column align="center" prop="status" label="状态">
          <template #default="{ row }">
            <el-tag v-if="row.status === '0'" type="success">正常</el-tag>
            <el-tag v-if="row.status === '1'" type="danger">关闭</el-tag>
          </template>
        </el-table-column>
      </template>
      <template v-else>
        <el-table-column align="center" prop="dictCode" label="字典编码" />
        <el-table-column align="center" prop="dictLabel" label="字典标签">
          <template #default="{ row }">
            <el-tag v-if="row.listClass" :type="row.listClass">{{ row.dictLabel }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="dictValue" label="字典键值" />
        <el-table-column align="center" prop="dictSort" label="字典排序" />
        <el-table-column align="center" prop="status" label="状态">
          <template #default="{ row }">
            <el-tag v-if="row.status === '0'" type="success">正常</el-tag>
            <el-tag v-if="row.status === '1'" type="danger">关闭</el-tag>
          </template>
        </el-table-column>
      </template>
      <el-table-column align="center" label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" :icon="EditPen" @click="rowEdit(row)">编辑</el-button>
          <el-button link type="primary" :icon="Delete" @click="rowDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :background="true"
      :current-page="pageable.pageNum"
      :page-size="pageable.pageSize"
      :page-sizes="[10, 25, 50, 100]"
      :total="pageable.total"
      :size="globalStore?.assemblySize ?? 'default'"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>

    <DictDataEdit ref="dictDataEditRef" @update="refreshData" />
  </div>
</template>

<script setup lang="ts">
import mittBus from "@/utils/mittBus";
import { onMounted, onUnmounted, reactive, ref } from "vue";
import { useGlobalStore } from "@/stores/modules/global";
import { getDictDataListApi, getDictTypeListApi, delDictTypeApi, delDictDataApi } from "@/api/modules/dict";
import { Delete, CirclePlus, Refresh, Search, EditPen } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import DictDataEdit from "./DictDataEdit.vue";

const globalStore = useGlobalStore();

// 默认显示字典类型列表
const dictTypeShow = ref(true);

const TypeInfo = ref();

onMounted(() => {
  // 默认加载类型列表
  getDictTypeList();
  mittBus.on("dictTypeChange", (data: any) => {
    if (data.dictId === 0) {
      dictTypeShow.value = true;
      TypeInfo.value = null;
      pageable.pageNum = 1;
      pageable.pageSize = 10;
      pageable.total = 0;
      getDictTypeList();
    } else {
      dictTypeShow.value = false;
      TypeInfo.value = data;
      pageable.pageNum = 1;
      pageable.pageSize = 10;
      pageable.total = 0;
      getDictDataList();
    }
  });
});

onUnmounted(() => {
  mittBus.off("dictTypeChange");
});

const tableData = ref([]);

const searchParam = ref({
  dictName: "",
  dictType: ""
});

interface Pageable {
  pageNum: number;
  pageSize: number;
  total: number;
}

const pageable = reactive<Pageable>({
  pageNum: 1,
  pageSize: 10,
  total: 0
});

const handleSizeChange = (val: number) => {
  pageable.pageSize = val;
  if (dictTypeShow.value) {
    getDictTypeList();
  } else {
    getDictDataList();
  }
};

const handleCurrentChange = (val: number) => {
  pageable.pageNum = val;
  if (dictTypeShow.value) {
    getDictTypeList();
  } else {
    getDictDataList();
  }
};

const getDictTypeList = async () => {
  const res = await getDictTypeListApi({
    dictName: searchParam.value.dictName,
    dictType: searchParam.value.dictType,
    pageNum: pageable.pageNum,
    pageSize: pageable.pageSize
  });
  if (res.code === 200) {
    tableData.value = res.data.list;
    pageable.total = res.data.total;
  }
};

const resetTypeList = () => {
  searchParam.value = {
    dictName: "",
    dictType: ""
  };
  pageable.pageNum = 1;
  pageable.pageSize = 10;
  pageable.total = 0;
  getDictTypeList();
};

const getDictDataList = async () => {
  const res = await getDictDataListApi({
    dictLabel: "",
    dictType: TypeInfo.value.dictType,
    pageNum: pageable.pageNum,
    pageSize: pageable.pageSize
  });
  if (res.code === 200) {
    tableData.value = res.data.list;
    pageable.total = res.data.total;
  }
};

const refreshData = () => {
  if (dictTypeShow.value) {
    getDictTypeList();
  } else {
    getDictDataList();
  }
};

const selection = ref([]);
const handleSelectionChange = (val: any) => {
  selection.value = val;
};
const delMsgBox = (delTitle: string, delIds: number[], confirm: (delIds: number[]) => void) => {
  ElMessageBox.confirm(delTitle, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      confirm(delIds);
    })
    .catch(() => {
      console.log("取消");
    });
};
const btnDelete = () => {
  if (dictTypeShow.value) {
    const dictIds = selection.value.map((item: any) => item.dictId);
    const delMsg = `是否确认删除字典编号为"${dictIds.join(",")}"的数据项?`;
    delMsgBox(delMsg, dictIds, dictIds => delDictType(dictIds));
  } else {
    const dictCodes = selection.value.map((item: any) => item.dictCode);
    const delMsg = `是否确认删除字典编号为"${dictCodes.join(",")}"的数据项?`;
    delMsgBox(delMsg, dictCodes, dictCodes => delDictData(dictCodes));
  }
};

// 行删除
const rowDelete = (row: any) => {
  if (dictTypeShow.value) {
    const dictIds = [row.dictId];
    const delMsg = `是否确认删除字典编号为"${dictIds.join(",")}"的数据项?`;
    delMsgBox(delMsg, dictIds, dictIds => delDictType(dictIds));
  } else {
    const dictCodes = [row.dictCode];
    const delMsg = `是否确认删除字典编号为"${dictCodes.join(",")}"的数据项?`;
    delMsgBox(delMsg, dictCodes, dictCodes => delDictData(dictCodes));
  }
};

const emit = defineEmits(["update", "addType", "editType"]);
const delDictType = async (dictIds: number[]) => {
  const res = await delDictTypeApi({ dictIds });
  if (res.code === 200) {
    ElMessage.success("删除成功");
    // 触发回调刷新左侧和右侧
    emit("update");
  } else {
    ElMessage.error(res.msg);
  }
};

const delDictData = async (dictCodes: number[]) => {
  const res = await delDictDataApi({ dictCodes });
  if (res.code === 200) {
    ElMessage.success("删除成功");
    getDictDataList();
  } else {
    ElMessage.error(res.msg);
  }
};
// 行编辑
const rowEdit = (row: any) => {
  if (dictTypeShow.value) {
    const rowData = {
      dictId: row.dictId,
      dictName: row.dictName,
      dictType: row.dictType,
      status: row.status
    };
    emit("editType", rowData);
  } else {
    const editData = {
      type: "edit",
      dictName: TypeInfo.value.dictName,
      dictType: TypeInfo.value.dictType,
      ...row
    };
    dictDataEditRef.value.openDialog(editData);
  }
};

const dictDataEditRef = ref();
const btnAdd = () => {
  if (dictTypeShow.value) {
    emit("addType");
  } else {
    const addData = {
      type: "add",
      dictName: TypeInfo.value.dictName,
      dictType: TypeInfo.value.dictType
    };
    dictDataEditRef.value.openDialog(addData);
  }
};

defineExpose({
  refreshData
});
</script>

<style scoped lang="scss">
.el-form-item {
  margin-bottom: 0;
}
</style>
